/* Copyright (c) 2008, John Cronin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "elf.h"
#include "console.h"
#include "vmem.h"
#include "stdlib.h"
#include "mboot.h"
#include "kif.h"
#include "memmgr.h"

#define DEFAULT_PIE_ALIGN		0x100000
#define DEFAULT_NONPIE_ALIGN	0x1000

static unsigned long int pie_base;
static void *k;
Elf64_Ehdr *ehdr;
static Elf64_Shdr *strtab = NULL;
static Elf64_Shdr *shstrtab = NULL;
static Elf64_Shdr *symtab = NULL;

int load_elf64_kernel(void *kernel, unsigned long long int *pml4t, unsigned long long int *e_point,
					  unsigned long long int *load_offset)
{
	int is_pie = 0;
	unsigned long long int image_start = 0xffffffff, image_end = 0;
	unsigned long int image_length;
	Elf64_Half phdr_idx;
	Elf64_Half shdr_idx;

	*e_point = 0;
	ehdr = (Elf64_Ehdr *)kernel;
	k = kernel;
	
	/* check this is an elf64 file */
	if((ehdr->e_ident[EI_MAG0] != 0x7f) || (ehdr->e_ident[EI_MAG1] != 'E') || (ehdr->e_ident[EI_MAG2] != 'L') ||
		(ehdr->e_ident[EI_MAG3] != 'F')) {
			puts("Error: not an ELF file");
			return -1;
	}
	if(ehdr->e_ident[EI_CLASS] != ELFCLASS64) {
		puts("Error: not an ELF64 file");
		return -1;
	}
	if(ehdr->e_ident[EI_DATA] != ELFDATA2LSB) {
		puts("Error: not an ELF64 LSB file");
		return -1;
	}

	/* determine the start and end addresses of the image, and thus its length */
	for(phdr_idx = 0; phdr_idx < ehdr->e_phnum; phdr_idx++) {
		Elf64_Phdr *phdr = (Elf64_Phdr *)(phdr_idx * ehdr->e_phentsize + (unsigned long int)ehdr->e_phoff +
			(unsigned long int)kernel);

		if(phdr->p_type == PT_LOAD) {
			if(phdr->p_vaddr < image_start)
				image_start = phdr->p_vaddr;
			if((phdr->p_vaddr + phdr->p_memsz) > image_end)
				image_end = phdr->p_vaddr;
		}
	}
	image_length = (unsigned long int)(image_end - image_start);
	if(image_length % DEFAULT_PIE_ALIGN)
		image_length = image_length - (image_length % DEFAULT_PIE_ALIGN) + DEFAULT_PIE_ALIGN;
#ifdef _DEBUG
	_puts("tysos: s: ", 0);
	puthex(image_start);
	_puts("  e: ", 0);
	puthex(image_end);
	_puts("  l: ", 0);
	puthex(image_length);
	_puts("", 1);
#endif

	/* determine whether its position-independent or not */
	if(ehdr->e_type == ET_EXEC)
		is_pie = 0;
	else if(ehdr->e_type == ET_DYN) {
		unsigned long int pie_excess;
		is_pie = 1;
		pie_base = (unsigned long int)malloc_align(image_length, DEFAULT_PIE_ALIGN, Tysos, 1);
		if(pie_base == (unsigned long int)NULL) {
			puts("Error: unable to allocate memory for kernel");
			return -1;
		}
		pie_excess = pie_base % DEFAULT_PIE_ALIGN;
		if(pie_excess != 0) {
			pie_base -= pie_excess;
			pie_base += DEFAULT_PIE_ALIGN;
		}

#ifdef _DEBUG
		_puts("load: ", 0);
		puthex(pie_base);
		_puts("-", 0);
		puthex(pie_base + image_length);
		_puts("", 1);
#endif
	}
	else {
		puts("Error: unknown file type (not ET_EXEC or ET_DYN)");
		return -1;
	}

	/* ensure its for the x86_64 processor */
	if(ehdr->e_machine != EM_X86_64) {
		puts("Error: not an x86_64 executable");
		return -1;
	}

	/* Iterate through the program headers, loading what is necessary */
	for(phdr_idx = 0; phdr_idx < ehdr->e_phnum; phdr_idx++) {
		Elf64_Phdr *phdr = (Elf64_Phdr *)(phdr_idx * ehdr->e_phentsize + (unsigned long int)ehdr->e_phoff +
			(unsigned long int)kernel);

		if((phdr->p_type == PT_LOAD) && (phdr->p_filesz + phdr->p_memsz > 0)) {
			unsigned long long int base;
			unsigned char *paddr_base;
			unsigned long long int f_count;

			base = phdr->p_vaddr;
			if(is_pie)
				base += pie_base;

			f_count = 0;

			paddr_base = NULL;
			while(f_count < phdr->p_memsz) {
				if(!paddr_base || !((base + f_count) & (PAGESIZE - 1))) {
					paddr_base = (unsigned char *)create_virtual_mapping(base + f_count, pml4t, phdr->p_flags, Tysos);
					if(paddr_base == NULL) {
						puts("Error: create_virtual_mapping returned NULL");
						return -1;
					}
				}

				if(f_count < phdr->p_filesz) {
					paddr_base[(base + f_count) & (PAGESIZE - 1)] = *((unsigned char *)((unsigned long int)kernel +
						(unsigned long int)phdr->p_offset + (unsigned long int)f_count));
				} else
					paddr_base[(base + f_count) & (PAGESIZE - 1)] = 0;

				f_count++;
			}
		}
	}

	/* Fix up dynamic relocations */
	if(is_pie) {
		for(shdr_idx = 0; shdr_idx < ehdr->e_shnum; shdr_idx++) {
			Elf64_Shdr *shdr = (Elf64_Shdr *)(shdr_idx * ehdr->e_shentsize + (unsigned long int)ehdr->e_shoff +
				(unsigned long int)kernel);

			if(shdr->sh_type == SHT_RELA) {
				Elf64_Off cur_off;

				for(cur_off = 0; cur_off < shdr->sh_size; cur_off += shdr->sh_entsize) {
					Elf64_Rela *rela = (Elf64_Rela *)(unsigned long int)(cur_off + shdr->sh_offset + (unsigned long int)kernel);

					if(ELF64_R_TYPE(rela->r_info) == R_X86_64_RELATIVE) {
						/* We need to set the 8-byte field at virtual address DEFAULT_PIE_OFFSET + rela->r_offset to
						DEFAULT_PIE_OFFSET + rela->r_addend */

						*((unsigned long long int *)(create_virtual_mapping(pie_base + rela->r_offset,
							pml4t, PF_W | PF_R, Tysos))) = pie_base + rela->r_addend;
					}
				}
			}
		}
	}

	/* Identify the section name string table */
	shstrtab = (Elf64_Shdr *)(ehdr->e_shstrndx * ehdr->e_shentsize + (unsigned long int)ehdr->e_shoff + (unsigned long int)kernel);

	/* Identify the symbol string table and symbol tables */
	for(shdr_idx = 0; shdr_idx < ehdr->e_shnum; shdr_idx++) {
		Elf64_Shdr *shdr = (Elf64_Shdr *)(shdr_idx * ehdr->e_shentsize + (unsigned long int)ehdr->e_shoff +
			(unsigned long int)kernel);
		char *sect_name = (char *)(shdr->sh_name + (unsigned long int)shstrtab->sh_offset + (unsigned long int)kernel);

		if(shdr->sh_type == SHT_SYMTAB)
			symtab = shdr;
		if(!strcmp(".strtab", sect_name))
			strtab = shdr;
	}
	/* Identify the entry point, first by looking for the symbol "_start" and then defaulting to ehdr->e_entry */
	if(symtab == NULL)
	{
#ifdef _DEBUG
		puts("Symbol table not found");
#endif
	}
	else if(strtab == NULL)
	{
#ifdef _DEBUG
		puts("String table not found");
#endif
	}
	else
	{
		Elf64_Off cur_off;
#ifdef _DEBUG
		_puts("symtab: ", 0);
		puthex((unsigned long int)symtab);
		_puts("  strtab: ", 0);
		puthex((unsigned long int)strtab);
		puts("");
#endif

		for(cur_off = 0; cur_off < symtab->sh_size; cur_off += symtab->sh_entsize) {
			Elf64_Sym *cur_sym = (Elf64_Sym *)(unsigned long int)(cur_off + symtab->sh_offset + (unsigned long int)kernel);
			char *sym_name = (char *)(cur_sym->st_name + (unsigned long int)strtab->sh_offset + (unsigned long int)kernel);
			if(!strcmp("_start", sym_name))
				*e_point = cur_sym->st_value;
		}	
	}
	if(*e_point == 0)
		*e_point = ehdr->e_entry;
	if(is_pie) {
		*e_point += pie_base;
		*load_offset = (unsigned long long int)pie_base;
	} else
		*load_offset = 0x0LL;

#ifdef _DEBUG
	_puts("epoint: ", 0);
	puthex((unsigned long int)*e_point);
	_puts("  load_offset: ", 0);
	puthex((unsigned long int)*load_offset);
	_puts("", 1);
#endif

	return 0;
}

uint64_t Get_Symbol_Addr(const char *name)
{
	Elf64_Off cur_off;
	if(symtab == NULL)
		puts("Get_Symbol_Addr failed: symtab not loaded");
	if(strtab == NULL)
		puts("Get_Symbol_Addr failed: strtab not loaded");

	for(cur_off = 0; cur_off < symtab->sh_size; cur_off += symtab->sh_entsize) {
		Elf64_Sym *cur_sym = (Elf64_Sym *)(unsigned long int)(cur_off + symtab->sh_offset + (unsigned long int)k);
		char *sym_name = (char *)(cur_sym->st_name + (unsigned long int)strtab->sh_offset + (unsigned long int)k);
		if(!strcmp(name, sym_name))
			return cur_sym->st_value;
	}
	return 0;
}
